package com.luhuiguo.cms.server.webdav;

import javax.inject.Inject;
import javax.inject.Named;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.BeanIds;
import org.springframework.security.core.AuthenticationException;

import com.bradmcevoy.http.Auth;
import com.bradmcevoy.http.Request;
import com.bradmcevoy.http.Resource;
import com.bradmcevoy.http.SecurityManager;
import com.bradmcevoy.http.Request.Method;
import com.bradmcevoy.http.http11.auth.DigestResponse;

public class SpringSecurityManager implements SecurityManager {

    private String realm;

    @Inject
    @Named(BeanIds.AUTHENTICATION_MANAGER)
    private AuthenticationManager authenticationManager;

    public SpringSecurityManager() {

    }

    public SpringSecurityManager(String realm) {
        this.realm = realm;
    }

    @Override
    public Object authenticate(DigestResponse digestRequest) {
        return null;
    }

    @Override
    public Object authenticate(String user, String password) {
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(user, password);
        try {
            return authenticationManager.authenticate(authRequest);
        } catch (AuthenticationException e) {
            return null;
        }
    }

    @Override
    public boolean authorise(Request request, Method method, Auth auth, Resource resource) {
        if (method.isWrite) {
            return auth != null && auth.getTag() != null;
        } else {
            return true;
        }

    }

    @Override
    public String getRealm(String host) {
        return realm;
    }

    public String getRealm() {
        return realm;
    }

    public void setRealm(String realm) {
        this.realm = realm;
    }

}
